<template>
  <div class="container">
    <div v-if="!is_publish">
      <el-steps direction="vertical" :active="active">
        <el-step title="步骤 1">
          <template slot="description">
            <div class="step">
              <h3>已经注册微信小程序，立即授权</h3>
              <p>
                使用微信小程序管理员账号扫码进行授权，授权过程中请勾选所有权限以确保小程序功能的完整性，如果未注册小程序，可以从公众号后台免微信认证创建小程序或者直接前往"微信公众平台"注册企业主体的小程序账号
              </p>
              <div class="step_bottom">
                <div v-show="auth_step == 1">
                  <el-button
                    type="primary"
                    @click="authApp"
                    v-repeatClick
                    :disabled="active != 1"
                    >{{ authAppbtn }}</el-button
                  >
                </div>
                <div class="step1_bottom2" v-show="auth_step == 2">
                  <p class="waiting">
                    <i class="el-icon-loading"></i>
                    <span>等待授权中...</span>
                  </p>
                </div>
                <div class="step1_bottom2" v-show="auth_step == 3">
                  <p class="success">
                    <i class="el-icon-circle-check"></i> <span>授权成功</span>
                  </p>
                </div>
                <div class="step1_bottom2" v-show="auth_step == 4">
                  <p class="cancel">
                    <i class="el-icon-error"></i> <span>已取消授权</span>
                  </p>
                  <span class="vertical">|</span>
                  <p class="fail" @click="authAgin" v-repeatClick>重新授权</p>
                </div>
              </div>
            </div>
          </template>
        </el-step>
        <el-step title="步骤 2">
          <template slot="description">
            <div class="step">
              <h3>完成验证，上传代码</h3>
              <p>填写版本号和小程序信息，并将小程序代码上传</p>
              <div class="step_bottom">
                <div class="step2_bottom2">
                  <div
                    v-show="!show_noteform && !upload_success"
                    class="step2_bottom2_header"
                  >
                    <el-button
                      type="primary"
                      @click="show_noteform = !show_noteform"
                      v-repeatClick
                      :disabled="active != 2"
                    >
                      填写信息
                    </el-button>
                  </div>
                  <div
                    v-show="!show_noteform && upload_success"
                    class="step2_bottom2_header"
                  >
                    <p class="success">
                      <i class="el-icon-success"></i>
                      <span>上传成功</span>
                    </p>
                    <span class="vertical">|</span>
                    <el-popover
                      placement="bottom-start"
                      width="200"
                      trigger="click"
                      @show="showQrcode"
                    >
                      <div class="qrcode">
                        <i
                          v-show="qrcode_loading"
                          class="icon el-icon-loading"
                        ></i>
                        <img v-show="img_src" :src="img_src" alt="" />
                      </div>
                      <p class="fail jump" slot="reference">小程序预览二维码</p>
                    </el-popover>
                    <span class="vertical">|</span>
                    <p class="cursor" @click="submitAgain" v-repeatClick>
                      重新上传
                    </p>
                    <span class="vertical">|</span>
                    <el-popover
                      placement="bottom-start"
                      width="200"
                      trigger="click"
                    >
                      <div>
                        <p>版本号：{{ noteform.user_version || "无" }}</p>
                        <p>版本信息：{{ noteform.user_desc || "无" }}</p>
                      </div>
                      <p class="cursor" slot="reference">版本信息</p>
                    </el-popover>
                  </div>
                  <el-collapse-transition>
                    <div v-if="show_noteform">
                      <el-form
                        :model="noteform"
                        label-width="80px"
                        :rules="rules"
                        ref="noteform"
                      >
                        <el-form-item label="版本号:" prop="user_version">
                          <el-input
                            v-model.trim="noteform.user_version"
                            placeholder="版本号"
                            clearable
                          ></el-input>
                        </el-form-item>
                        <el-form-item label="版本描述:" prop="user_desc">
                          <el-input
                            v-model.trim="noteform.user_desc"
                            placeholder="版本描述"
                            clearable
                          ></el-input>
                        </el-form-item>
                        <el-form-item label=""
                          ><el-button
                            :disabled="active != 2"
                            @click="submitCommit"
                            v-repeatClick
                            >上传代码</el-button
                          >
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-collapse-transition>
                </div>
              </div>
            </div>
          </template>
        </el-step>
        <el-step title="步骤 3">
          <template slot="description">
            <div class="step">
              <h3>完成所有步骤，提交审核并发布小程序</h3>
              <p>提交微信审核(最长需14个工作日),审核通过后即可立即发布版本</p>
              <div class="step_bottom">
                <div v-show="verify_step == 1">
                  <el-button
                    type="primary"
                    @click="submitAudit"
                    v-repeatClick
                    :disabled="active != 3"
                    >{{ verify_btn_content }}</el-button
                  >
                </div>
                <div class="step2_bottom2" v-show="verify_step == 2">
                  <div class="step2_bottom2_header">
                    <p>
                      <i class="el-icon-loading"></i>
                      <span>提交审核中，请耐心等待</span>
                    </p>
                    <span class="vertical">|</span>
                    <p class="cursor" @click="getAuditStatus" v-repeatClick>
                      查询审核状态
                    </p>
                    <span class="vertical">|</span>
                    <p
                      style="color: red"
                      class="cursor"
                      @click="undoCodeAudit"
                      v-repeatClick
                    >
                      撤销审核
                    </p>
                  </div>
                  <p v-show="show_verify_status" style="padding-left: 20px">
                    {{ verify_status }}
                  </p>
                  <p
                    v-show="show_verify_reason"
                    v-html="verify_reason"
                    style="padding-left: 20px; color: red"
                  ></p>
                </div>
                <div class="step2_bottom2" v-show="verify_step == 3">
                  <p class="success">
                    <el-button
                      type="primary"
                      @click="release"
                      v-repeatClick
                      :disabled="active != 3"
                    >
                      <span>发布小程序</span></el-button
                    >
                  </p>
                </div>
                <div class="step2_bottom2" v-show="verify_step == 4">
                  <div class="step2_bottom2_header">
                    <p class="fail">
                      <i class="el-icon-error"></i>
                      <span>{{ verify_fail_content }}</span>
                    </p>
                    <span class="vertical">|</span>
                    <p
                      style="cursor: pointer"
                      class="fail"
                      @click="submitAudit"
                      v-repeatClick
                    >
                      重新审核
                    </p>
                    <span class="vertical">|</span>
                    <p>
                      <a href="https://mp.weixin.qq.com/" target="_blank"
                        >前往微信公众平台</a
                      >
                    </p>
                  </div>
                  <div class="fail_content" v-html="verify_reason"></div>
                </div>
              </div>
            </div>
          </template>
        </el-step>
      </el-steps>
    </div>
    <div class="is_public" v-else>
      <svg aria-hidden="true" class="main_page_svg" width="110" height="110">
        <use xlink:href="#icon-success" />
      </svg>
      <p>小程序已发布</p>
      <p>敬请期待新版本更新</p>
    </div>
  </div>
</template>
<script>
import {
  authApp,
  queryAuth,
  getAuth,
  commit,
  getQrcode,
  submitAudit,
  getAuditStatus,
  release,
  undoCodeAudit,
  getRequestUrl,
  setRequestUrl,
} from "@/api/global/globalUploadWxApp";
import { mapGetters } from "vuex";
export default {
  name: "",
  props: {
    app_id: {
      type: String,
    },
    wx_miniapp_data: {
      type: Object,
      default: {},
    },
  },
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      active: 1,
      // 步骤一
      is_publish: false,
      timer: "",
      authAppbtn: "立即授权",
      auth_step: 1, //1  立即授权    2正在授权   3授权成功   4取消授权
      // 步骤二
      noteform: {
        user_version: null,
        user_desc: null,
      },
      rules: {
        user_version: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
          { min: 1, max: 64, message: "长度在1-64个字符", trigger: "blur" },
        ],
        user_desc: [
          { required: true, message: "版本描述不能为空", trigger: "blur" },
          { min: 1, max: 64, message: "长度在1-64个字符", trigger: "blur" },
        ],
      },
      show_noteform: false,
      upload_success: false,
      img_src: "",
      qrcode_loading: true,
      // 步骤三
      verify_btn_content: "提交审核",
      verify_step: 1, //1  提交审核    2正在审核当中  3审核成功   4审核失败
      show_verify_status: false,
      verify_status: "",
      show_verify_reason: false,
      verify_reason: "",
      verify_fail_content: "审核失败",
    };
  },
  watch: {
    wx_miniapp_data: {
      handler(val) {
        let { is_publish, audit } = val;
        let res = audit;
        if (is_publish) {
          this.is_publish = is_publish;
          return;
        }
        if (res.errcode == 0) {
          if (res.status == "审核成功") {
            this.active = 3;
            this.verify_step = 3;
            return;
          }
          if (res.status == "审核被拒绝" || res.status == "审核延后") {
            this.active = 3;
            this.verify_fail_content = res.status;
            this.verify_step = 4;
            this.verify_status = res.status;
            this.show_verify_status = true;
            this.verify_reason = res.reason;
            this.show_verify_reason = true;
            return;
          }
          if (res.status == "已撤回") {
            this.active = 1;
            this.auth_step = 1;
            this.authAppbtn = "立即授权";
          }
          if (res.status == "审核中") {
            this.active = 3;
            this.verify_step = 2;
            this.verify_status = res.status;
            this.show_verify_status = true;
            this.verify_reason = res.reason;
            this.show_verify_reason = true;
          }
        } else if (res.errcode == 40016) {
          this.active = 1;
          this.auth_step = 1;
          this.authAppbtn = "立即授权";
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    // 立即授权
    authApp() {
      this.auth_step = 2;
      let data = {
        app_id: this.app_id,
      };
      authApp(data).then((res) => {
        if (res.errcode == 0) {
          let url = res.data.url;
          window.open(`http://new.caidj.net.cn/wxThirdAuth/?url=${url}`);
          console.log(`http://new.caidj.net.cn/wxThirdAuth/?url=${url}`);
          // window.open(url);
          this.timer = setInterval(() => {
            this.getAuth().then((res) => {
              if (res.errcode == 0) {
                this.auth_step = 3;
                clearInterval(this.timer);
                this.timer = null;
                this.queryAuth().then((res) => {
                  if (res.errcode == 0) {
                    this.active = 2;
                  } else if (res.errcode == 40016 || res.errcode == 40011) {
                    this.active = 1;
                    this.auth_step = 4;
                    this.$message.error(res.errmsg);
                  }
                });
              } else if (res.errcode == 10) {
                this.auth_step = 4;
                clearInterval(this.timer);
                this.timer = null;
              }
            });
          }, 1000);
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 成功后获取token
    queryAuth() {
      let data = {
        app_id: this.app_id,
      };
      return new Promise((resolve) => {
        queryAuth(data).then((res) => {
          resolve(res);
        });
      });
    },
    // 重新授权
    authAgin() {
      this.authApp();
    },
    clearTime() {
      clearInterval(this.timer);
      this.timer = null;
    },
    // 授权结果轮询
    getAuth() {
      let data = {
        app_id: this.app_id,
      };
      return new Promise((resolve) => {
        getAuth(data).then((res) => {
          resolve(res);
        });
      });
    },
    // 上传代码
    async submitCommit() {
      this.$refs["noteform"].validate(async (valid) => {
        if (valid) {
          let data = Object.assign(this.noteform, { app_id: this.app_id });
          let setResponse = await this.setRequest();
          if (setResponse == 0) {
            return;
          }
          commit(data).then((res) => {
            if (res.errcode == 0) {
              this.show_noteform = false;
              this.upload_success = true;
              localStorage.setItem("uploadWx", JSON.stringify(this.noteform));
              this.active = 3;
            } else if (res.errcode == "40016") {
              this.active = 1;
              this.auth_step = 4;
              this.$message.error(res.errmsg);
              this.show_noteform = false;
            } else if (res.errcode == "40011") {
              this.$message.error(res.errmsg);
            }
          });
        }
      });
    },
    // 重新上传
    submitAgain() {
      this.show_noteform = true;
      this.upload_success = false;
      this.active = 2;
    },
    // 显示二维码
    showQrcode() {
      let data = {
        app_id: this.app_id,
      };
      getQrcode(data).then((res) => {
        if (res.errcode == 0) {
          let img_src = res.path;
          this.img_src = img_src;
          this.qrcode_loading = false;
        } else if (res.errcode == "40016") {
          this.active = 1;
          this.auth_step = 4;
          this.$message.error(res.errmsg);
          this.show_noteform = false;
        }
      });
    },
    // 提交审核
    submitAudit() {
      this.verify_step = 1;
      let data = {
        app_id: this.app_id,
      };
      submitAudit(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("提交成功");
          this.verify_step = 2;
          this.show_verify_status = true;
          this.verify_status = "审核中";
          this.verify_reason = "";
          this.show_verify_reason = false;
        } else if (res.errcode == 40011) {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 撤销审核
    undoCodeAudit() {
      let data = {
        app_id: this.app_id,
      };
      undoCodeAudit(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.success("撤销成功");
          this.active = 3;
          this.verify_step = 1;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 设置请求的地址
    async setRequest() {
      let res = await this.getRequestUrl();
      return new Promise((resolve, reject) => {
        if (res.errcode == 0) {
          resolve(1);
        } else if (res.errcode == 40080) {
          this.setRequestUrl().then((res) => {
            if (res.errcode == 0) {
              resolve(1);
            } else {
              this.$message.error(res.errmsg);
              resolve(0);
            }
          });
        } else if (res.errcode == 40011) {
          this.$message.error(res.errmsg);
          resolve(0);
        }
      });
    },
    getRequestUrl() {
      let data = {
        app_id: this.app_id,
      };
      return new Promise((resolve, reject) => {
        getRequestUrl(data).then((res) => {
          resolve(res);
        });
      });
    },
    setRequestUrl() {
      let data = {
        app_id: this.app_id,
      };
      return new Promise((resolve, reject) => {
        setRequestUrl(data).then((res) => {
          resolve(res);
        });
      });
    },
    // 查询审核结果
    getAuditStatus() {
      let data = {
        app_id: this.app_id,
      };
      getAuditStatus(data).then((res) => {
        if (res.errcode == 0) {
          if (res.status == "审核成功") {
            this.verify_step = 3;
            return;
          }
          if (res.status == "审核被拒绝" || res.status == "已撤回") {
            this.verify_fail_content = res.status;
            this.verify_step = 4;
            return;
          }

          this.verify_status = res.status;
          this.show_verify_status = true;
          this.verify_reason = res.reason;
          this.show_verify_reason = true;
        } else if (res.errcode == 40016) {
          this.active = 1;
          this.auth_step = 1;
          this.authAppbtn = "立即授权";
        }
      });
    },
    // 发布小程序
    release() {
      let data = {
        app_id: this.app_id,
      };
      release(data).then((res) => {
        if (res.errcode == 0) {
          this.$message.error("发布成功");
          this.is_publish = true;
        } else {
          this.$message.success(res.errmsg);
        }
      });
    },
  },
  created() {
    let str = localStorage.getItem("uploadWx");
    if (str) {
      let obj = JSON.parse(str);
      this.noteform.user_version = obj.user_version;
      this.noteform.user_desc = obj.user_desc;
    }
  },
};
</script>
<style lang='scss' scoped>
.container {
  width: 100%;
  height: 100%;
  min-height: 400px;
  padding: 0 40px;
}
/deep/ .el-step__head.is-finish {
  color: #03a98e;
  border-color: #03a98e;
}
/deep/.el-step__title.is-finish {
  color: #03a98e;
}
/deep/.el-step__description {
  padding-right: 0;
}
.step {
  color: #606266;
  padding: 0 20px;
  h3 {
    font-size: 18px;
    padding: 5px 0;
  }
  .step_bottom {
    margin: 10px 0 15px 0;
    display: flex;
    align-items: center;
  }
  .step1_bottom2 {
    display: flex;
    align-items: center;
    .success {
      color: #03a98e;
      font-size: 14px;
      font-weight: 500;
      display: flex;
      align-items: center;
      .el-icon-circle-check {
        font-weight: 700;
        font-size: 16px;
        padding-right: 5px;
      }
    }
    .waiting {
      color: #e6a23c;
      font-size: 14px;
      display: flex;
      align-items: center;
      span {
        padding-left: 6px;
      }
    }
    .vertical {
      font-size: 16px;
      padding: 0 10px;
    }
    .fail {
      cursor: pointer;
      user-select: none;
      &:hover {
        color: red;
      }
    }
    .cancel {
      color: #e6a23c;
      font-size: 14px;
      font-weight: 500;
      display: flex;
      align-items: center;
      .el-icon-error {
        font-weight: 700;
        font-size: 16px;
        padding-right: 6px;
      }
    }
  }
  .step2_bottom2 {
    .step2_bottom2_header {
      display: flex;
      align-items: center;
      p {
        font-size: 14px;
        font-weight: 500;
        .el-icon-loading {
          font-weight: 700;
          font-size: 16px;
        }
      }
      .vertical {
        font-size: 16px;
        padding: 0 10px;
      }
      .fail {
        color: #f56c6c;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;

        .el-icon-error {
          font-weight: 700;
          font-size: 16px;
          padding-right: 5px;
        }
      }
      .jump {
        cursor: pointer;
        user-select: none;
      }
      .success {
        color: #03a98e;
        font-size: 14px;
        font-weight: 500;
        display: flex;
        align-items: center;
        .el-icon-circle-check {
          font-weight: 700;
          font-size: 16px;
          padding-right: 5px;
        }
      }
      .cursor {
        cursor: pointer;
      }
    }
    .fail_content {
      padding-left: 21px;
      color: #f56c6c;
    }
  }
}
.is_public {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  .main_page_svg {
    margin: 70px 0 20px 0;
  }
  p {
    font-size: 16px;
    line-height: 1.5;
  }
}
.qrcode {
  width: 175px;
  height: 175px;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  icon {
    position: absolute;
    margin: 0 auto;
    top: 80px;
    font-size: 18px;
  }
  img {
    display: block;
    width: 100%;
    max-height: 100%;
  }
}
</style>
